package com.ygqh.baby.controller.mobile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.handler.CommitOrderHandler;
import com.ygqh.baby.handler.SettlementHandler;
import com.ygqh.baby.handler.ShoppingCarHandler;
import com.ygqh.baby.model.BaseSkuInfo;
import com.ygqh.baby.model.CarPackPriceResult;
import com.ygqh.baby.model.CommitOrderRequestParam;
import com.ygqh.baby.model.YgShoppingCarModel;
import com.ygqh.baby.po.YgOrder;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.service.*;
import com.ygqh.baby.utils.SessionUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单
 *
 * @author guohao
 */
@Controller
@RequestMapping("/app/order")
public class YgOrderController extends BaseController {

    @Autowired
    private YgShoppingCarService shoppingCarService;
    @Autowired
    private YgOrderService orderService;
    @Autowired
    private YgUserService userService;
    @Autowired
    private YgOrderLogService ygOrderLogService;
    @Autowired
    private YgSkuService skuService;
    @Autowired
    private TrustoneService trustoneService;
    @Autowired
    private CommitOrderHandler commitOrderHandler;
    @Autowired
    private SettlementHandler settlementHandler;
    @Autowired
    private YgBmdismService ygBmdismService;
    @Autowired
    private ShoppingCarHandler shoppingCarHandler;

    /**
     * 跳转到结算页面
     *
     * @param skuIds 商品SKU ID集
     * @return
     */
    @RequestMapping(value = "toSettlementPage")
    @ResponseBody
    public ResponseEntity toSettlementPage(Long[] skuIds) {
        YgUser user = SessionUtil.getCurrentUser();
        Message message = settlementHandler.toSettlementPage(skuIds, user.getId(), false, SALES_PLATFORM);
        return ResponseEntity.converter(message);
    }

    /**
     * 获取商品数据
     *
     * @return
     */
    @RequestMapping(value = "findItemInfo")
    @ResponseBody
    public ResponseEntity findItemInfo() {
        YgUser user = SessionUtil.getCurrentUser();
        Map<String, Object> map = new HashMap<>();
        List<YgShoppingCarModel> list = shoppingCarService.findIsCheck(user.getId(), false, SALES_PLATFORM);
        //设置多买多折标记
        ygBmdismService.getBestBmdism(list);
        shoppingCarService.doNewCusBussness(list);
        List<List<YgShoppingCarModel>> sortCarList = shoppingCarService.sortCarList(list, user.getId());
        CarPackPriceResult disAndSpecialPrice = shoppingCarHandler.getPackAndNewCustomDisAndSpecialPrice(list);
        map.put("carList", sortCarList);
        map.put("productPrice", disAndSpecialPrice.getProductPrice());
        map.put("specialPrice", disAndSpecialPrice.getSpecialPrice());
        map.put("vipDisPrice", disAndSpecialPrice.getVipDisPrice());
        map.put("trustoneFlag", trustoneService.validateIsTrustonerOrder(list));
        return ResponseEntity.success(map);
    }

    /**
     * 删除订单
     *
     * @param orderId 订单编号
     * @return
     */
    @RequestMapping(value = "delete")
    @ResponseBody
    public ResponseEntity delete(Long orderId) {
        YgUser user = SessionUtil.getCurrentUser();
        int row = orderService.deleteSoft(orderId, user.getId());
        return ResponseEntity.success(row);
    }

    /**
     * 确认收货
     *
     * @param orderId 订单编号
     * @return
     */
    @RequestMapping(value = "confirmReceipt")
    @ResponseBody
    public ResponseEntity confirmReceipt(Long orderId) {
        YgUser user = SessionUtil.getCurrentUser();
        Message msg = orderService.confirmReceipt(orderId, user.getId());
        return ResponseEntity.converter(msg);
    }

    /**
     * 取消订单
     *
     * @param orderId 订单编号
     * @return
     */
    @RequestMapping(value = "cancelOrder")
    @ResponseBody
    public ResponseEntity cancelOrder(Long orderId, String cancelReason) {
        YgUser user = SessionUtil.getCurrentUser();
        orderService.cancelOrder(orderId, user.getId(), user.getUserName(), cancelReason);
        Boolean isNewCustom = userService.isNewCustom(user.getId());
        return ResponseEntity.success(isNewCustom);
    }

    /**
     * 零元订单支付完成
     *
     * @param orderId 订单编号
     * @return
     */
    @RequestMapping(value = "completeZeroOrder")
    @ResponseBody
    public ResponseEntity completeZeroOrder(Long orderId) {
        YgUser user = SessionUtil.getCurrentUser();
        YgOrder order = orderService.findByOrderId(orderId);
        if (order == null || order.getUserId().longValue() != user.getId().longValue()
                || order.getTotalPrice().compareTo(BigDecimal.ZERO) != 0) {
            return ResponseEntity.error("订单编号有误或金额不符");
        }

        int i = orderService.splitOrderV2(orderId, new BigDecimal(0), PayType.Account);
        if (i == 0) {
            return ResponseEntity.error("订单金额有误请核对订单");
        }

        return ResponseEntity.success(null);
    }

    /**
     * 提交订单
     *
     * @param requestParam 订单提交参数
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "commitOrder")
    @ResponseBody
    public ResponseEntity commitOrder(CommitOrderRequestParam requestParam) {
        YgUser user = SessionUtil.getCurrentUser();
        if (StringUtils.isBlank(requestParam.getPlatformNo())) {
            requestParam.setPlatformNo(PLATFORM_NO);
        }
        ygOrderLogService.addOrderLog(user.getId(), OrderStatus.WaitingPay, user.getUserName(),
                "提交订单,【入参】：requestParam=" + requestParam.toString());

        List<YgShoppingCarModel> carList = shoppingCarService.findIsCheck(user.getId(), false, SALES_PLATFORM);
        // 保存订单
        Message msg = commitOrderHandler.commitOrder(user.getId(), user.getUserName(), requestParam.getUserAddressId(),
                requestParam.getCouponDetailId(), requestParam.getTotalPrice(), requestParam.getAppType(),
                requestParam.getPayType(), requestParam.getSourceCode(), requestParam.getAccountPrice(),
                requestParam.getFormId(), requestParam.getUserRemark(), requestParam.getExpressCardId(),
                requestParam.getOrderType(), carList, requestParam.getPlatformNo(), requestParam.getIdentityNo(),
                SALES_PLATFORM);
        // 订单保存成功
        if (msg.getType().equals(Message.Type.success)) {
            Map<String, Object> map = (Map<String, Object>) msg.getExtra();
            map.put("totalPrice", requestParam.getTotalPrice().subtract(requestParam.getAccountPrice()));
            msg.setExtra(map);
            msg.setContent("订单提交成功");
            ygOrderLogService.addOrderLog((Long) map.get("orderId"), OrderStatus.WaitingPay, user.getUserName(),
                    "订单提交成功：" + map.toString());
        } else {
            logger.info("订单提交失败，userId：" + user.getId() + ";" +
                    "msgType:" + msg.getType() + ";" +
                    "msg:" + msg.getContent() + ";" +
                    "msgExtra:" + (msg.getExtra() == null ? "" : msg.getExtra().toString()));
        }
        return ResponseEntity.converter(msg);
    }

    /**
     * 查询订单是否支付成功
     *
     * @param orderId 订单编号
     * @return
     */
    @RequestMapping(value = "isPaySuccess")
    @ResponseBody
    public ResponseEntity isPaySuccess(Long orderId) {
        YgOrder order = orderService.findByOrderId(orderId);
        List<OrderStatus> orderStautss = new ArrayList<>();
        orderStautss.add(OrderStatus.TradeClosed);
        orderStautss.add(OrderStatus.WaitingPay);
        if (!orderStautss.contains(order.getOrderStatus())) {
            return ResponseEntity.success(true);
        } else {
            return ResponseEntity.success(false);

        }
    }

    /**
     * 商品信息（立即购买）
     *
     * @param skuInfos SKU信息集
     * @return
     */
    @RequestMapping(value = "findItemInfoForPayNow", method = RequestMethod.GET)
    public String findItemInfoForPayNow(String skuInfos) {
        return skuService.checkSkuInfoIsGroup(skuInfos) ? "forward:/mobile/grouporder/findItemInfoPt.do" : "forward:/mobile/order/findItemInfoWithSkuInfo.do";
    }

    @RequestMapping(value = "findItemInfoWithSkuInfo", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity findItemInfoWithSkuInfo(String skuInfos) {
        YgUser user = SessionUtil.getCurrentUser();
        Map<String, Object> map = new HashMap<>();
        List<BaseSkuInfo> skuList = JSON.parseObject(skuInfos, new TypeReference<List<BaseSkuInfo>>() {
        });

        List<YgShoppingCarModel> carList = shoppingCarService.findItemInfo(skuList, user.getId(),
                PromotionType.Ordinary, false, SALES_PLATFORM);
        List<List<YgShoppingCarModel>> sortCarList = shoppingCarService.sortCarListV2(carList, user.getId());
        Map<String, BigDecimal> priceMap = orderService.getProductPrice(carList);
        map.put("carList", sortCarList);
        map.put("productPrice", priceMap.get("productPrice"));
        map.put("specialPrice", priceMap.get("specialPrice"));
        map.put("vipDisPrice", priceMap.get("vipDisPrice"));
        map.put("trustoneFlag", trustoneService.validateIsTrustonerOrder(carList));
        return ResponseEntity.success(map);
    }

    /**
     * 提交订单（立即购买）
     *
     * @param orderRequestParam 订单提交参数
     * @param request           request
     * @return
     */
    @RequestMapping(value = "commitOrderForPayNow")
    public String commitOrderForPayNow(CommitOrderRequestParam orderRequestParam, HttpServletRequest request) {
        orderRequestParam.setOrderType(orderRequestParam.getOrderType() == null ? OrderType.CardCoupon : orderRequestParam.getOrderType());
        orderRequestParam.setUserAddressId(orderRequestParam.getUserAddressId() == null ? 0L : orderRequestParam.getUserAddressId());
        request.setAttribute("sourceOrderType", orderRequestParam.getOrderType().name());
        return skuService.checkSkuInfoIsGroup(orderRequestParam.getSkuInfos()) ? "forward:/app/grouporder/commitOrderPt.do"
                : "forward:/app/order/commitOrderWithSkuInfo.do";
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "commitOrderWithSkuInfo")
    @ResponseBody
    public ResponseEntity commitOrderWithSkuInfo(CommitOrderRequestParam orderRequestParam) {
        YgUser user = SessionUtil.getCurrentUser();
        String openid = user.getOpenId();
        if (StringUtils.isBlank(orderRequestParam.getPlatformNo())) {
            orderRequestParam.setPlatformNo(PLATFORM_NO);
        }

        ygOrderLogService.addOrderLog(user.getId(), OrderStatus.WaitingPay, user.getUserName(),
                "提交订单,【入参】：" + orderRequestParam.toString());

        List<YgShoppingCarModel> carList = shoppingCarService.findItemInfo(orderRequestParam.getSkuList(), user.getId(),
                PromotionType.Ordinary, orderRequestParam.getDistribution(), SALES_PLATFORM);

        // 保存订单
        Message msg = commitOrderHandler.commitOrder(user.getId(), user.getUserName(), orderRequestParam.getUserAddressId(),
                orderRequestParam.getCouponDetailId(), orderRequestParam.getTotalPrice(), orderRequestParam.getAppType(),
                orderRequestParam.getPayType(), orderRequestParam.getSourceCode(), orderRequestParam.getAccountPrice(),
                orderRequestParam.getFormId(), orderRequestParam.getUserRemark(), orderRequestParam.getExpressCardId(),
                orderRequestParam.getOrderType(), carList, orderRequestParam.getPlatformNo(), orderRequestParam.getIdentityNo(),
                SALES_PLATFORM);

        // 订单保存成功
        if (msg.getType().equals(Message.Type.success)) {
            Map<String, Object> map = (Map<String, Object>) msg.getExtra();
            map.put("openid", openid);
            map.put("totalPrice", orderRequestParam.getTotalPrice().subtract(orderRequestParam.getAccountPrice()));
            msg.setExtra(map);
            msg.setContent("订单提交成功");
            ygOrderLogService.addOrderLog((Long) map.get("orderId"), OrderStatus.WaitingPay, user.getUserName(), "订单提交成功：" + map.toString());
        } else {
            logger.info("订单提交失败，userId：" + user.getId() + ";msgType:" + msg.getType() + ";msg:" + msg.getContent() + ";msgExtra:"
                    + (msg.getExtra() == null ? "" : msg.getExtra().toString()));
        }
        return ResponseEntity.converter(msg);
    }

    @RequestMapping("/getTotalSharePrice")
    @ResponseBody
    public ResponseEntity getTotalSharePrice(@RequestParam Long orderId) {
        BigDecimal totalSharePrice = orderService.getTotalSharePrice(orderId);
        return ResponseEntity.success(totalSharePrice);

    }
}
